package com.zhong.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhong.blog.mapper.GuestbookMapper;
import com.zhong.blog.pojo.Essay;
import com.zhong.blog.pojo.Guestbook;
import com.zhong.blog.pojo.User;
import com.zhong.blog.service.GuestbookService;
import com.zhong.blog.service.UserService;
import com.zhong.blog.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/guest")
public class GuestbookController {

    @Autowired
    GuestbookService guestbookService;
    @Autowired
    GuestbookMapper guestbookMapper;
    @Autowired
    UserService userService;

    @PostMapping("/save")
    public R saveGuestbook(@RequestBody Guestbook guestbook){

        List<User> users = userService.queryByName(guestbook.getUsername());
        guestbook.setImgurl(users.get(0).getImgurl());

        guestbookService.save(guestbook);
        return R.ok();
    }


    @GetMapping("/getData")
    public R getData(@RequestParam("page") int page,@RequestParam("size") int size){

        QueryWrapper<Guestbook> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        Page<Guestbook> guestbookPage = new Page<>(page, size);
        guestbookMapper.selectPage(guestbookPage, wrapper);
        List<Guestbook> guestbooks = guestbookPage.getRecords();
        long total = guestbookPage.getTotal();
        return R.ok().put("guestbooks",guestbooks).put("total",total);
    }

}
